/*
 * @Descripttion: 
 * @version: 
 * @Author: ydj
 * @Date: 2025-04-09 10:44:00
 * @LastEditors: ydj
 * @LastEditTime: 2025-04-09 17:29:36
 */
import React, { useState, useMemo } from "react";
import { usePosition } from "../../contexts/PositionContext";
import { getCurrentPosition } from "../../utils/getCurrentPosition.ts";
import BaiduMap from "../BaiduMap/baiduMap.tsx";
import "./style.scss";

const WePosition: React.FC = () => {
    // 从Context获取pos和setPos
    const { pos, setPos } = usePosition();
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // 保留原有的缓存逻辑
    const memoizedCoords = useMemo(() => {
        if (!pos) return null;
        return {
            lng: pos[0],
            lat: pos[1],
            timestamp: Date.now()
        };
    }, [pos]);

    const handleGetPosition = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const coords = await getCurrentPosition();
            setPos(coords); // 使用来自Context的setPos
        } catch (error) {
            console.error("获取位置失败:", error);
            setError("获取位置失败，请确保已授权位置权限" + error);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="container">
            
            <div className="mapBox">
                <BaiduMap lng={pos[0]} lat={pos[1]} zoom={20}></BaiduMap>
            </div>

            <div className="position-container">
                <button
                    className="position-button"
                    onClick={handleGetPosition}
                    disabled={isLoading}
                >
                    {isLoading ? "获取中..." : "点击获取当前位置"}
                </button>
                {error && <div className="error-message">{error}</div>}
                {memoizedCoords && (
                    <div className="coordinates">
                        经度: {memoizedCoords.lng.toFixed(2)}&nbsp;
                        纬度: {memoizedCoords.lat.toFixed(2)}
                    </div>
                )}
            </div>

        </div>
    );
};

export default WePosition;